package com.example.spring.multi.aop.annotation.aspect;

import com.alibaba.fastjson.JSONObject;
import com.example.spring.multi.aop.annotation.Log;
import com.example.spring.multi.utils.RequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Aspect
@Component
@Slf4j
public class LogAspect {



    private final static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(30, 60, 180L, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
    ;

    public LogAspect() {

    }

    // 配置织入点
    @Pointcut("@annotation(com.example.spring.multi.aop.annotation.Log)")
    public void logPointCut() {
    }

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "logPointCut()", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Object jsonResult) {
        saveLog(joinPoint, null, jsonResult);
    }

    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e         异常
     */
    @AfterThrowing(value = "logPointCut()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
        saveLog(joinPoint, e, null);
    }

    /**
     * 处理日志
     *
     * @param joinPoint 切面对象
     * @param exception 异常
     * @param result    返回值
     * @author xiaohan.yuan
     */
    protected void saveLog(final JoinPoint joinPoint, final Exception exception, Object result) {
        try {
            // 获得注解
            Log controllerLog = getAnnotationLog(joinPoint);
            if (controllerLog == null) {
                return;
            }



            // 获取请求参数
            HttpServletRequest request = RequestUtil.getRequest();
            if (request != null) {
                String requestURI = request.getRequestURI();
                String method = request.getMethod();
                Map<?, ?> paramsMap = (Map<?, ?>) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
                if (Objects.isNull(paramsMap)||paramsMap.size() == 0){
                }else {
                    String s = JSONObject.toJSONString(paramsMap);
                }

            }

            // 获取返回的参数
            String resultJsonStr = JSONObject.toJSONString(result);


            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            // 调用方法


            /*获取注解参数*/
            // 模块名

            threadPoolExecutor.execute(() -> // 保存日志
            {
                // 保存日志
            });
        } catch (Exception e) {
            // 记录本地异常日志
            log.error("==前置通知异常==");
            log.error("异常信息:{}", e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private Log getAnnotationLog(JoinPoint joinPoint) throws Exception {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null) {
            return method.getAnnotation(Log.class);
        }
        return null;
    }



}
